/*
 * 0054. String to Integer (atoi)
 * 实现atoi这个函数，将一个字符串转换为整数。如果没有合法的整数，返回0。如果整数超出了32位整数的范围，返回INT_MAX(2147483647)如果是正整数，或者INT_MIN(-2147483648)如果是负整数。
 * https://www.lintcode.com/problem/string-to-integer-atoi/description
 * 
 * 样例
 * "10" =>10
 * "-1" => -1
 * "123123123123123" => 2147483647
 * "1.0" => 1
 * 
 * 2018.06.29 @jeyming
 */
package string_to_integer_atoi_0054;

public class String_to_integer_atoi_0054 {
	/**
	 * @param str: A string
	 * @return: An integer
	 */
	public int atoi(String str) {
		// write your code here
		int start = 0;	//记录数字的开始
		int end = str.length();	//记录数字的结束
		boolean judge = false;	//判断正负
		boolean judgeStart = false;	//判断是否存在数字
		for(int i = 0; i < str.length(); ++i) {
			if(judgeStart == false) {
				if(str.charAt(i) == '-') {
					judgeStart = true;
					judge = true;
					start = i + 1;
				}
				if(str.charAt(i) == '+'){
					judgeStart = true;
					start = i + 1;
				}
				if((str.charAt(i) >= '0') && (str.charAt(i) <= '9')) {
					judgeStart = true;
					start = i;
				}
			} else {
				if(str.charAt(i) == '.') {
					end = i;
					break;
				} 
				if((str.charAt(i) < '0') || (str.charAt(i) > '9')) {
					end = i;
					break;
				}
			}
		}
		//System.out.println("start=" + start + " end=" + end);
		if((end - start) >= 10) {
			if(judge == false){
				return 2147483647;
			} else {
				return -2147483648;
			}
		}
		int num = 0;
		for(int i = start; (i < end) && (judgeStart); ++i) {
			num = num * 10 + (str.charAt(i) - '0');
		}
		if(judge){
			num = -num;
		}
		return num;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
